package com.ssm.service.Impl;

import com.ssm.entity.ResourceUrl;
import com.ssm.entity.RoleResourceURL;
import com.ssm.mapper.ResourceUrlMapper;
import com.ssm.mapper.RoleResourceUrlMapper;
import com.ssm.service.ResourcesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * security在拉起加载时需要将所有的角色资源信息进行加载，以用于角色授权时使用
 */
@Service
public class ResourcesServiceImpl implements ResourcesService {

    @Autowired
    private ResourceUrlMapper resourceUrlMapper;

    @Autowired
    private RoleResourceUrlMapper roleResourceUrlMapper;

    /**
     * 获取所有URL
     * @return
     */
    @Override
    public List<ResourceUrl> getAllResourceURL() {
        List<ResourceUrl> allResourceURL = resourceUrlMapper.getAllResourceURL();
        return allResourceURL;
    }

    /**
     * 遍历资源URL来查找每一个URL的对应拥有权限的角色
     * URL 1 - 角色 n
     * @return
     */
    @Override
    public Map<String,Collection<ConfigAttribute>> getAllRolesByResourceURL() {
        Map<String,Collection<ConfigAttribute>> resourceURLRoles = new HashMap<String,Collection<ConfigAttribute>>();
        List<ResourceUrl> resourceURLs = getAllResourceURL();
        for (ResourceUrl resourceURL : resourceURLs ){
            List<RoleResourceURL> roleResourceURL =  roleResourceUrlMapper.getAllRolesByResourceId(resourceURL.getResourceId());
            Collection<ConfigAttribute> roles = new ArrayList<ConfigAttribute>();
            for (RoleResourceURL roleResourceURL1 : roleResourceURL){
                ConfigAttribute configAttribute = new SecurityConfig(roleResourceURL1.getRole());
                roles.add(configAttribute);
            }
            resourceURLRoles.put(resourceURL.getResourceString(),roles);
        }
        return resourceURLRoles;
    }
}
